package io.netty.example.helloworld.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Server {
    public static void main(String[] args) throws Exception{
        //configure the server
        //创建两个 eventLoopGroup 对象
        //创建boss线程组 用于服务器接受客户端的连接
        EventLoopGroup bossGroup = new NioEventLoopGroup(100);
        //create worker thread to use socketChannel data read and write
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            //create ServerBootstrap 对象object
            ServerBootstrap b = new ServerBootstrap();
            //set up use EvnetLoopstrap object
            b.group(bossGroup,workerGroup)
                    //设置要被实例化的为 NioServerSocketChannel 类
                    .channel(NioServerSocketChannel.class)
                    //设置 NioServerSocketChannel的处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //设置连入服务器的Client 的socketchannel 的处理器
                    .childHandler(new ServerInitializer());

            //绑定端口 并且同步等待成功 就是启动服务器端
            ChannelFuture f = b.bind("127.0.0.1",8888);
            //监听服务器关闭 并阻塞等待
            f.channel().closeFuture().sync();
            System.out.println("服务器开始运行 端口 :8888");


        } finally {
            //优雅的关闭两个EventloopGroup 对象
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
